﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SQLTouch.Client.Metro.Cache;
using SQLTouch.Client.Metro.View.Explore;
using SQLTouch.Client.Metro.View.Home;
using SQLTouch.Client.Metro.ViewModel;
using SQLTouch.Client.Metro.ViewModel.Explore;
using SQLTouch.Client.Metro.ViewModel.Home;
using SQLTouch.Service.DataContracts;
using SQLTouch.Service.Proxies;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace SQLTouch.Client.Metro
{
    sealed partial class App : Application, INavigator
    {
        private readonly TouchProxy touchProxy;
        private readonly RoamingCache<DatabaseData> databaseCache;
        private readonly RoamingCache<QueryData> queryCache;
        private readonly Facade facade;

        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            this.touchProxy = new TouchProxy("http://localhost:52426/TouchService.svc");
            this.databaseCache = new RoamingCache<DatabaseData>("databases", p => p.Id.ToString());
            this.queryCache = new RoamingCache<QueryData>("queries", p => p.Id.ToString());
            this.facade = new Facade(this, databaseCache, queryCache, touchProxy);
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                //if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                //{
                //    throw new Exception("Failed to create initial page");
                //}
                GoToHome();
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }

        private void ShowPopup(Page page, Func<Popup, VMBase> viewModelFunction)
        {
            Popup popup = new Popup();
            popup.Child = page;
            page.DataContext = viewModelFunction(popup);
            popup.IsOpen = true;
        }

        private void Navigate(Type pageType, VMBase viewModel)
        {
            Frame rootFrame = (Frame)Window.Current.Content;
            rootFrame.Navigate(pageType, viewModel);
        }

        public void GoToHome()
        {
            Navigate(typeof(HomeView), new HomeVM(facade));
        }

        public void GoToExplore(DatabaseData database)
        {
            Navigate(typeof(ExploreView), new ExploreVM(facade, database));
        }

        public void ShowAddDatabase()
        {
            ShowPopup(new AddDatabaseView(), p => new AddDatabaseVM(facade, new PopupService(p)));
        }

        public void ShowEditDatabase(DatabaseData database)
        {
            ShowPopup(new EditDatabaseView(), p => new EditDatabaseVM(facade, new PopupService(p), database));
        }

        public void ShowDeleteDatabase(DatabaseData database)
        {
            ShowPopup(new DeleteDatabaseView(), p => new DeleteDatabaseVM(facade, new PopupService(p), database));
        }

        public void ShowAddQuery(DatabaseData database)
        {
            ShowPopup(new AddQueryView(), p => new AddQueryVM(facade, new PopupService(p), database));
        }

        public void ShowEditQuery(QueryData query)
        {
            throw new NotImplementedException();
        }

        public void ShowDeleteQuery(QueryData query)
        {
            throw new NotImplementedException();
        }

        public async void ShowUnexpectedError(string errorMessage, Exception exception)
        {
            MessageDialog dialog = new MessageDialog(errorMessage + "\nDetails: " + exception.Message, "Unexpected error");
            await dialog.ShowAsync();
        }

        public async void ShowUnexpectedError(string errorMessage)
        {
            MessageDialog dialog = new MessageDialog(errorMessage, "Unexpected error");
            await dialog.ShowAsync();
        }
    }
}
